<template>
  <div class="register">
    <div class="register-main">
      <h2>注册账号</h2>
      <van-form>
        <van-field
          v-model="nickname"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '密码不少于6位' }, {pattern:/^\w{6,}$/}]"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit" @click="register">
            提交
          </van-button>
        </div>
      </van-form>
      <div class="toLogin">
        <p>
          <router-link to="/login">已有账号？请登录</router-link>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Form } from 'vant'

Vue.use(Form)

export default {
  data () {
    return {
      password: '',
      nickname: ''
    }
  },
  methods: {
    register () {
      if (this.password === '') {
        return
      }
      if (
        !this.password.match(/^\w{6,}$/)
      ) {
        return
      }
      let users = localStorage.users
      if (users) {
        users = JSON.parse(users)
      } else {
        users = []
      }
      users.push({
        nickname: this.nickname,
        password: this.password
      })
      localStorage.users = JSON.stringify(users)
      this.$notify({
        type: 'success',
        message: '注册成功！'
      })
      setTimeout(() => {
        this.$router.push({
          path: '/login'
        })
      }, 1000)
    }
  }
}
</script>

<style lang="scss">
* {
  margin: 0;
  padding: 0;
}
html,
body,
.register {
  height: 100%;
}
.register {
  display: flex;
  flex-direction: column;
}
.register-main {
  flex: 1;
  padding: 200px 0;
  text-align: center;
  h2{
    line-height: 3;
    color: #1989fa;
  }
}
.toLogin {
  p {
    line-height: 2;
    color: blue;
    font-size: 12px;
  }
}
</style>
